package Util;


import io.reactivex.Single;
import io.reactivex.functions.Function;
import io.vertx.reactivex.ext.sql.SQLClient;
import io.vertx.reactivex.ext.sql.SQLConnection;



public class SQLUtil {


    private static Single<SQLConnection> getConnection(SQLClient sqlClient) {
        return sqlClient.rxGetConnection()
                .doOnError(err -> {
                    System.out.println("打开据库连接失败");
                    err.printStackTrace();
                });
    }

    public static <T> Single<T> doInConnection(SQLClient sqlClient, Function<? super SQLConnection, ? extends Single<T>> func) {

        return Single.defer(() ->
                getConnection(sqlClient)
                        .flatMap(conn ->
                                func.apply(conn)
                                        .doOnError(err -> {
                                            System.out.println("执行sql发生错误");
                                            err.printStackTrace();
                                        })
                                        .doAfterTerminate(conn::close)
                        ));
    }


}

